//
//  UIView+Alignment.m
//  JSToolkit
//
//  Created by 정재성 on 2013. 11. 2..
//  Copyright (c) 2013년 정재성. All rights reserved.
//

#import "UIView+Alignment.h"
#import "UIView+Frame.h"

@implementation UIView (Alignment)

- (void)alignmentTo:(UIViewAlignment)alignment
{
    [self alignmentTo:alignment ofRect:self.superview.bounds margins:UIEdgeInsetsZero];
}

- (void)alignmentTo:(UIViewAlignment)alignment margins:(UIEdgeInsets)margins
{
    [self alignmentTo:alignment ofRect:self.superview.bounds margins:margins];
}

- (void)alignmentTo:(UIViewAlignment)alignment ofRect:(CGRect)rect
{
    [self alignmentTo:alignment ofRect:rect margins:UIEdgeInsetsZero];
}

- (void)alignmentTo:(UIViewAlignment)alignment ofRect:(CGRect)rect margins:(UIEdgeInsets)margins
{
    if (alignment & UIViewAlignmentLeft)
        self.x = rect.origin.x + margins.left;
    else if (alignment & UIViewAlignmentRight)
        self.x = rect.origin.x + rect.size.width - self.width - margins.right;
    else if (alignment & UIViewAlignmentCenterHorizontal)
        self.x = rect.origin.x + (rect.size.width - self.width) / 2.0f;

    if (alignment & UIViewAlignmentTop)
        self.y = rect.origin.y + margins.top;
    else if (alignment & UIViewAlignmentBottom)
        self.y = rect.origin.y + rect.size.height - self.height - margins.bottom;
    else if (alignment & UIViewAlignmentCenterVertical)
        self.y = rect.origin.y + (rect.size.height - self.height) /2.0f;
}

@end
